import api from '@/utils/api'
import type { Product, User } from '@/types/product'

// 用户认证相关接口
export const authService = {
  // 用户登录
  async login(username: string, password: string) {
    const response = await api.post('/auth/login/', { username, password })
    return response.data
  },

  // 用户注册
  async register(username: string, email: string, password: string) {
    const userData: any = { username, password }
    if (email) userData.email = email
    
    const response = await api.post('/auth/register/', userData)
    return response.data
  },

  // 用户登出
  async logout() {
    const response = await api.post('/auth/logout/')
    return response.data
  },

  // 刷新token
  async refresh_token(refresh:string){
    const response = await api.post('/auth/refresh/', {refresh})
    return response.data;
  },

  //获取头像URL
  async getUserAvatarURL(userId: number) {
    const response = await api.get(`/auth/${userId}/avatar/`)
    return response.data
  },
}

// 商品管理相关接口
export const productService = {
  // 获取商品列表
  async getProducts(page: number = 1, search?: string, category?: string) {
    const params: Record<string, any> = { page }
    //搜索
    if (search) params.search = search
    //种类
    if (category) params.category = category
    
    const response = await api.get('/products/', { params })
    return response.data
  },

  // 获取用户发布的商品列表
  async getUserProducts(userId: number, page: number = 1) {
    const params: Record<string, any> = { page, uid: userId }
    
    const response = await api.get('/products/', { params })
    return response.data
  },

  // 获取商品详情
  async getProductDetail(id: number) {
    const response = await api.get(`/products/${id}/`)
    return response.data
  },

  // 创建商品
  async createProduct(formData: FormData) {
    const response = await api.post('/products/create/', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })
    return response.data
  },

  // 更新商品
  async updateProduct(id: number, formData: FormData) {
    const response = await api.put(`/products/update/${id}/`, formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })
    return response.data
  },

  // 删除商品
  async deleteProduct(id: number) {
    const response = await api.delete(`/products/delete/${id}/`)
    return response.data
  }
}
